/**
 * 
 */
package cn.com.xf.web.controller.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;
import cn.com.xf.domain.TblOaSoft;
import cn.com.xf.domain.TblSiteResume;
import cn.com.xf.service.SiteService;
import cn.com.xf.service.SoftService;
import cn.com.xf.utils.ImageUtils;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.form.BaseForm;

/**
 * @author Administrator
 * 
 */
@Controller
public class UploadController extends AbstractBaseController {

	@Autowired
	private SoftService softService;
	@Autowired
	private SiteService siteService;

	Log log = LogFactory.getLog(UploadController.class);

	/**
	 * KindEditor上传统一入口，上传图片和文件
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload4KindEditor")
	public void upload4KindEditor(HttpServletRequest request, HttpServletResponse response, BaseForm form)
			throws Exception {
		String type = form.getDir();
		// 判断是否显示文件空间
		if (StringUtils.isNotBlank(form.getDir()) && StringUtils.isNotBlank(form.getOrder())) {
			String fileString = getFileManage(request, form);
			response.setContentType("application/json; charset=UTF-8");
			response.getWriter().append(fileString);
			return;
		}
		// 上传文件
		if (!StringUtils.isNotBlank(type))
			return;
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put(
				"file",
				"doc,docx,xls,xlsx,ppt,pdf,exe,tif,xml,iso,htm,html,txt,zip,rar,gz,bz2,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,swf,flv,f4v,gif,jpg,jpeg,png,bmp");
		String saveUrl = "";
		MultipartFile file = form.getImgFile();
		if (null == file) {
			log.warn("上传的文件为空");
		}
		if (null == file.getBytes()) {
			log.warn("上传的文件的大小为空");
		}
		if (0 == file.getBytes().length) {
			log.warn("上传的文件的大小为0");
		}
		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
				+ file.getOriginalFilename();
		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
				.toLowerCase();
		if (Constants.UPLOAD_TYPE_IMAGE.equalsIgnoreCase(type)) {
			// 1.检查图片扩展名
			if (!Arrays.<String> asList(extMap.get("image").split(",")).contains(fileExt)) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("error", "1");
				map.put("message", "图片扩展名错误");
				String s = org.json.simple.JSONObject.toJSONString(map);
				response.getWriter().println(s);
				return;
			}
			// 2.检查图片的真实性
			if (null == ImageUtils.checkImage(file.getBytes())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("error", "1");
				map.put("message", "不是图片");
				String s = org.json.simple.JSONObject.toJSONString(map);
				response.getWriter().println(s);
				return;
			}
			// 3.存储到绝对目录下
			String absoluteImagePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_IMAGE_PATH;
			File imageFile = new File(absoluteImagePath);
			if (!imageFile.exists()) {
				imageFile.mkdirs();
			}
			File absoluteImageFile = new File(absoluteImagePath, newFileName);
			file.transferTo(absoluteImageFile);
			saveUrl = request.getContextPath() + "/imagextra/" + newFileName;
		} else if (Constants.UPLOAD_TYPE_FILE.equalsIgnoreCase(type)) {
			// 1.检查文件的扩展名
			if (!Arrays.<String> asList(extMap.get("file").split(",")).contains(fileExt)) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("error", "1");
				map.put("message", "文件扩展名错误");
				String s = org.json.simple.JSONObject.toJSONString(map);
				response.getWriter().println(s);
				return;
			}
			// 2.存储到绝对目录下
			String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_FILE_PATH;
			File fileFile = new File(absoluteFilePath);
			if (!fileFile.exists()) {
				fileFile.mkdirs();
			}
			File absoluteFileFile = new File(absoluteFilePath, newFileName);
			file.transferTo(absoluteFileFile);
			saveUrl = request.getContextPath() + "/filextra/" + newFileName;
		}

		// 返回链接
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("error", 0);
		map.put("url", saveUrl);
		String s = org.json.simple.JSONObject.toJSONString(map);
		response.getWriter().println(s);
	}

	/**
	 * 作废
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download2")
	public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		String fileId = request.getParameter("file");
		TblOaSoft soft = softService.selectById(Integer.valueOf(EncrypTool.dencode(fileId)));
		String fileName = soft.getDownfileName();
		String downLoadPath = request.getSession().getServletContext().getRealPath("/") + Constants.UPLOAD_PATH_FILE
				+ "\\" + fileName;
		try {
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	/**
	 * 作废
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downloadResume22")
	public ModelAndView downloadResume(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		String fileId = request.getParameter("file");
		TblSiteResume resume = siteService.selectResumeById(EncrypTool.dencode(fileId));
		String fileName = resume.getDoc();
		String downLoadPath = request.getSession().getServletContext().getRealPath("/") + Constants.UPLOAD_PATH_RESUME
				+ "\\" + fileName;
		try {
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	/**
	 * 文件空间
	 * 
	 * @param request
	 * @param form
	 * @return
	 */
	private String getFileManage(HttpServletRequest request, BaseForm form) {
		String dirReq = form.getDir();
		String orderReq = form.getOrder();
		String pathReq = form.getPath();

		// 1.获取文件的真实目录
		String rootPath = "";
		String rootUrl = "";
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		String dirName = dirReq;
		if (dirName != null) {
			if (!Arrays.<String> asList(new String[] { "image", "file" }).contains(dirName)) {
				return "Invalid Directory name.";
			}
			if ("image".equalsIgnoreCase(dirName)) {
				rootPath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
						+ Constants.ABSOLUTE_ROOT_IMAGE_PATH;
				rootUrl = request.getContextPath() + "/imagextra/";
			} else if ("file".equalsIgnoreCase(dirName)) {
				rootPath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
						+ Constants.ABSOLUTE_ROOT_FILE_PATH;
				rootUrl = request.getContextPath() + "/filextra/";
			}
			File saveDirFile = new File(rootPath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
		}
		String path = pathReq != null ? pathReq : "";
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		// 排序形式，name or size or type
		String order = orderReq != null ? orderReq.toLowerCase() : "name";

		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			return "Invalid Directory name.";
		}
		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			return "Invalid Directory name.";
		}
		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if (!currentPathFile.isDirectory()) {
			return "Invalid Directory name.";
		}

		// 2. 遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if (file.isFile()) {
					if (!fileName.equalsIgnoreCase(".svn")) {
						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						hash.put("is_dir", false);
						hash.put("has_file", false);
						hash.put("filesize", file.length());
						hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
						hash.put("filetype", fileExt);
						hash.put("filename", fileName);
						hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
						fileList.add(hash);
					}
				}
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
			// 按照时间排序一次
			Collections.sort(fileList, new DateComparator());
		}

		currentUrl = rootUrl;
		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

		return result.toJSONString();
	}

	class NameComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
			}
		}
	}

	class SizeComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
					return 1;
				} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}

	class TypeComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
			}
		}
	}

	class DateComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				Date at = null;
				Date bt = null;
				try {
					at = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(hashA.get("datetime") + "");
					bt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(hashB.get("datetime") + "");
				} catch (ParseException e) {
					e.printStackTrace();
				}
				if (at.getTime() > bt.getTime()) {
					return -1;
				} else if (at.getTime() < bt.getTime()) {
					return 1;
				} else {
					return 0;
				}
			}
		}
	}
}
